﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MergeInfo.Modal.DAO;
using MergeInfo.Modal.Entity;
using MergeInfo.Modal.Exception;
using MergeInfo.Modal.Interface.IBLL;
using MergeInfo.Modal.Interface.IDAO;

namespace MergeInfo.Modal.BLL
{
    public class DataDictionaryBll : IDataDictionaryBll
    {
        private readonly IDataDictionaryDao _dataDictionaryDao;

        public DataDictionaryBll()
        {
            _dataDictionaryDao = new DataDictionaryDao();
        }

        public DataDictionaryEntity Save(DataDictionaryEntity dataDictionaryEntity)
        {
            IList<DataDictionaryEntity> dataDictionaryEntities = Select(dataDictionaryEntity.Name);
            if (dataDictionaryEntities.Count > 1)
                throw new DataDictionaryException("DataDictionary数据异常：name=" + dataDictionaryEntity.Name);
            if (dataDictionaryEntities.Count == 1)
                return dataDictionaryEntities[0];
            return New(dataDictionaryEntity);
        }

        public DataDictionaryEntity New(DataDictionaryEntity dataDictionaryEntity)
        {
            dataDictionaryEntity.Id = GetMaxId(dataDictionaryEntity.RId.Id, dataDictionaryEntity.Id);
            dataDictionaryEntity.Id++;
            _dataDictionaryDao.Create(dataDictionaryEntity);
            return dataDictionaryEntity;
        }

        public IList<DataDictionaryEntity> Select(string name)
        {
            return _dataDictionaryDao.Select(name);
        }

        private int GetMaxId(int rid,int id)
        {
            IList<DataDictionaryEntity> dataDictionaryEntities = _dataDictionaryDao.Select(rid);
            int maxId = id;
            if (dataDictionaryEntities.Count == 0)
                maxId = maxId * 1000;
            else
                maxId = dataDictionaryEntities.Max(d => d.Id);
            return maxId;
        }
    }
}
